package namespace

import (
	"krm-backend/config"
	"krm-backend/controllers"
	"krm-backend/controllers/configmap"
	"krm-backend/controllers/cronjob"
	"krm-backend/controllers/daemonset"
	"krm-backend/controllers/deployment"
	"krm-backend/controllers/secret"
	"krm-backend/controllers/service"
	"krm-backend/controllers/statefulset"

	"krm-backend/utils/logs"

	"github.com/dotbalo/kubeutils/kubeutils"
	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
)

func Copy(r *gin.Context) {
	logs.Debug(nil, "拷贝Namespace数据")
	var info controllers.Info
	//获取源集群Kubeconfig
	srckubeconfig := controllers.NewInfo(r, &info, "复制成功")
	//获取目标集群的Kubeconfig
	destkubeconfig := config.ClusterKubeconfig[info.DestClusterId]
	//1.先去处理namespace
	var namespace corev1.Namespace
	namespace.Name = info.DestNamespace
	nsInstance := kubeutils.NewNamespace(destkubeconfig, &namespace)
	var err error
	if info.CreateNamespace {
		//说明是新建namespace
		err = nsInstance.Create(info.DestNamespace)
	} else {
		//说明复制到现有的namespace
		_, err = nsInstance.Get(info.DestNamespace)
	}
	if err != nil {
		info.ReturnData.Message = err.Error()
		info.ReturnData.Status = 400
		r.JSON(200, info.ReturnData)
		return
	}
	//2.处理资源拷贝
	//2.1拿到每种类型的数据
	for resource, list := range info.Resources {
		// logs.Debug(map[string]interface{}{"resource":resource, "list":list"})
		switch resource {
		case "Deployment":
			deployment.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "StatefulSet":
			statefulset.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "DaemonSet":
			daemonset.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "CronJob":
			cronjob.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "Service":
			service.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "ConfigMap":
			configmap.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)

		case "secret":
			secret.Copy(srckubeconfig, destkubeconfig, info.Namespace, info.DestNamespace, list)
		}
	}
	r.JSON(200, info.ReturnData)

}
